package com.example.demo.aop;

import com.example.demo.DynamicDataSource.DataSourceContext;
import com.example.demo.entity.DataSourceConfig;
import com.example.demo.service.DatabaseService;
import com.example.demo.utils.DynamicDataSourceUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * aop打印日志信息
 * 和数据源更换
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect {
    @Autowired
    private DatabaseService databaseService;



    public DataSourceAspect() {
    }


    /**
     * 定义请求日志切入点，其切入点表达式有多种匹配方式,这里是指定路径
     */
    @Pointcut("execution(public * com.example.demo.controller.*.*(..))")
    //@Pointcut("@annotation(com.example.demo.annotation.AutoDynamicDataSource)")
    public void dataSourcePointcut() {
    }

    /**
     * 前置通知：
     * 1. 在执行目标方法之前执行，比如请求接口之前的登录验证;
     * 2. 在前置通知中设置请求日志信息，如开始时间，请求参数，注解内容等
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("dataSourcePointcut()")
    public void doBefore(JoinPoint joinPoint) {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取请求头中的User-Agent
        String userAgent = request.getHeader("User-Agent");

        //获取数据源指定信息
        String dataSourceName = request.getHeader("Data-Source-Name");
        if(StringUtils.isNotEmpty(dataSourceName)){
            DataSourceConfig otherDataSourceEntity = databaseService.findByName(dataSourceName);
            if(otherDataSourceEntity!=null){
                DynamicDataSourceUtil.generateDynamicDataSource(otherDataSourceEntity);
            }
        }

        //打印请求的内容
        log.info("请求Url : {}" , request.getRequestURL().toString());
        log.info("请求方式 : {}" , request.getMethod());
        log.info("请求ip : {}" , request.getRemoteAddr());
        log.info("请求方法 : {}" , joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("请求参数 : {}" , Arrays.toString(joinPoint.getArgs()));
        log.info("系统信息 : {}" ,userAgent);
        log.info("数据源信息 : {}" , dataSourceName);
    }

    /**
     * 方法环绕
     * @param joinPoint
     */
    @Around("dataSourcePointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        String method = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getName();

        Object ret = joinPoint.proceed();
        log.info("API request completed," + className + "." + method + " cost time "
                + (System.currentTimeMillis() - begin) + "ms");
        return ret ;
    }


    /**
     * 返回通知：
     * 1. 在目标方法正常结束之后执行
     * 1. 在返回通知中补充请求日志信息，如返回时间，方法耗时，返回值，并且保存日志信息
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "dataSourcePointcut()")
    public void doAfterReturning(Object ret){
        // 处理完请求，返回内容
        Gson gson = new Gson();
        log.info("请求返回 : {}" , gson.toJson(ret));

        //还原为默认数据源
        DataSourceContext.toDefault();
    }

    /**
     * 异常通知：
     * 1. 在目标方法非正常结束，发生异常或者抛出异常时执行
     * 1. 在异常通知中设置异常信息，并将其保存
     *
     * @param throwable
     */
    @AfterThrowing(value = "dataSourcePointcut()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        // 保存异常日志记录
        log.error("发生异常时间：{}" , LocalDateTime.now());
        log.error("抛出异常：{}" , throwable.getMessage());
        //还原为默认数据源
        DataSourceContext.toDefault();
    }
}